#ifndef WIFI_MANAGER_H
#define WIFI_MANAGER_H

#include <WiFi.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include <SD.h>
#include <DNSServer.h>
#include <Preferences.h>
#include "pattern_loader.h"
#include "motion_controller.h"
#include "led_manager.h"

// 前向声明
class LEDControlCenter;

class WiFiManager {
private:
  // ==================== 静态常量定义 ====================
  static constexpr int MAX_RECONNECT_ATTEMPTS = 5;
  static constexpr int MAX_CONNECTION_ATTEMPTS = 30;
  static constexpr unsigned long WIFI_CHECK_INTERVAL = 30000;      // 30秒检查一次
  static constexpr unsigned long CONNECTION_TIMEOUT = 15000;       // 15秒连接超时
  static constexpr unsigned long DNS_START_RETRY_DELAY = 1000;     // DNS启动重试延迟
  static constexpr unsigned long AP_CONFIG_DELAY = 500;            // AP配置延迟
  static constexpr unsigned long WIFI_DISCONNECT_DELAY = 100;      // WiFi断开延迟
  static constexpr unsigned long STATUS_DEBUG_INTERVAL = 30000;    // 状态调试输出间隔
  static constexpr int DEFAULT_AP_PORT = 80;
  static constexpr int DEFAULT_WEB_PORT = 80;
  static constexpr float RETRY_BACKOFF_MULTIPLIER = 1.5f;
  
  // AP模式IP配置
  static constexpr uint8_t AP_IP[4] = {192, 168, 4, 1};      // 192.168.4.1
  static constexpr uint8_t AP_GATEWAY[4] = {192, 168, 4, 1}; // 192.168.4.1  
  static constexpr uint8_t AP_SUBNET[4] = {255, 255, 255, 0}; // 255.255.255.0
  
  // ==================== 成员变量 ====================
  WebServer* server;
  DNSServer* dnsServer;
  PatternLoader* patternLoader;
  MotionController* motionController;
  LEDManager* ledManager;
  LEDControlCenter* ledControlCenter;
  Preferences preferences;
  String ssid;
  String password;
  bool wifiConnected;
  bool serverRunning;
  bool apMode;
  String apSSID;
  String apPassword;
  
  // WiFi监控相关
  unsigned long lastWiFiCheck;
  bool wifiMonitoring;
  int reconnectAttempts;
  unsigned long lastRetryTime;
  int currentRetryDelay;
  
  // ==================== 性能监控统计 ====================
  struct WiFiStats {
    unsigned long totalConnections = 0;
    unsigned long successfulConnections = 0;
    unsigned long failedConnections = 0;
    unsigned long totalDisconnections = 0;
    unsigned long currentConnectionStart = 0;
    unsigned long longestConnectionTime = 0;
    int bestSignalStrength = -100;
    int worstSignalStrength = 0;
    unsigned long totalDataTransferred = 0;
    unsigned long webRequests = 0;
    unsigned long portalRequests = 0;
  } stats;
  
  // ==================== 内部辅助方法 ====================
  bool configureAPMode();
  bool startDNSServer();
  bool setupWebRoutes();
  void setupCaptivePortalRoutes();
  void setupMainWebRoutes();
  void updateConnectionStats(bool connected);
  void updateSignalStats();
  void logPerformanceMetrics();
  void sendConfigErrorPage(const String& errorMsg);
  void sendConnectingPage(const String& ssid);
  bool validateSSID(const String& ssid);
  void handleAsyncWiFiConnection(const String& ssid, const String& password);
  IPAddress getAPIP() const { return IPAddress(AP_IP[0], AP_IP[1], AP_IP[2], AP_IP[3]); }
  IPAddress getAPGateway() const { return IPAddress(AP_GATEWAY[0], AP_GATEWAY[1], AP_GATEWAY[2], AP_GATEWAY[3]); }
  IPAddress getAPSubnet() const { return IPAddress(AP_SUBNET[0], AP_SUBNET[1], AP_SUBNET[2], AP_SUBNET[3]); }
  
  // Web服务器相关
  void handleRoot();
  void handleUpload();
  void handleFileUpload();
  void handleDownload();
  void handleFileList();
  void handleStatus();
  void handleControl();
  void handleNotFound();
  
  // Captive Portal相关
  void handleCaptivePortal();
  void handleWiFiConfig();
  void handleWiFiSave();
  void handleWiFiReset();
  void handleNetworkTest();
  bool isIPInRange(IPAddress ip);
  
  // 下载相关
  bool downloadFile(const String& url, const String& filename);
  void sendJsonResponse(int code, const String& message);
  
  // WiFi凭证存储
  void saveWiFiCredentials(const String& ssid, const String& password);
  bool loadWiFiCredentials();
  
public:
  WiFiManager(PatternLoader* loader, MotionController* motion, MotionController* motionForHoming, LEDManager* led = nullptr);
  ~WiFiManager();
  
  // 初始化和配网
  void begin();
  bool startConfigPortal(const String& apName = "沙画绘图机", const String& apPass = "");
  void stopConfigPortal();
  bool autoConnect();
  
  // WiFi连接
  bool connectWiFi(const String& ssid, const String& password);
  void disconnectWiFi();
  bool isConnected();
  String getIP();
  bool isAPMode();
  
  // Web服务器
  bool startWebServer(int port = 80);
  void stopWebServer();
  void handleClient();
  
  // 文件下载
  bool downloadPattern(const String& url, const String& filename);
  bool downloadPatternWithProgress(const String& url, const String& filename, 
                                   std::function<void(int)> progressCallback = nullptr);
  
  // WiFi状态监控
  void startWiFiMonitoring();
  void stopWiFiMonitoring();
  bool checkWiFiStatus();
  void handleWiFiReconnect();
  
  // ==================== 状态信息接口 ====================
  void printStatus();
  void printNetworkInfo();
  String getWiFiStatusString();
  int getSignalStrength();
  
  // ==================== 性能监控接口 ====================
  const WiFiStats& getStats() const { return stats; }
  void resetStats();
  void printPerformanceReport();
  String getPerformanceJson();
  
  // ==================== 扩展功能接口 ====================
  void downloadDefaultPatterns();
  void clearWiFiCredentials();
  void setLEDControlCenter(LEDControlCenter* center) { ledControlCenter = center; }
  
  // ==================== 模板方法优化 ====================
  template<typename T>
  void logWithTimestamp(const T& message) {
    Serial.print("[");
    Serial.print(millis());
    Serial.print("ms] ");
    Serial.println(message);
  }
  
  template<size_t N>
  bool validateJsonMessage(const char* jsonStr) {
    StaticJsonDocument<N> doc;
    DeserializationError error = deserializeJson(doc, jsonStr);
    return error == DeserializationError::Ok;
  }
  
private:
  String getHttpErrorDescription(int code);
};

#endif // WIFI_MANAGER_H
